import React, {useImperativeHandle, useRef, useState} from "react"
import ReactDOM from "react-dom"
import {designComponent, useReference} from "../../src";

interface Refer {
    sayHello: () => void,
    name: string,
}

/*const Child: React.FC<{
    name: string,
    age?: number,
    ref?: null | { current: Refer | null | undefined } | ((val: Refer | null | undefined) => void)
}> = React.forwardRef((props, ref) => {

    const inputRef = useRef<any>()
    useImperativeHandle(ref, () => {
        console.log('run useImperativeHandle')
        return {
            sayHello: () => inputRef.current.focus(),
            name: 'yes',
        }
    }, [])

    return (
        <div>
            <h2>this is child</h2>
            <input type="text" ref={inputRef}/>
        </div>
    )
})*/

const Child = designComponent({
    props: {
        name: {type: String},
        age: {type: Number},
    },
    setup({props}) {
        const inputRef = useReference<HTMLInputElement>()
        return {
            refer: {
                sayHello: () => inputRef.current!.focus(),
                name: 'yes',
            },
            render: () => (
                <div>
                    <h2>this is child</h2>
                    <input type="text" ref={inputRef}/>
                </div>
            )
        }
    },
})

/*
*  1. key变化重新渲染的时候，是新的组件先ref还是旧的组件先unref：（旧的组件先unref，接着是新的组件ref）
*  2. 会不会对designClassComponent的ref引用有影响
*  3. mount一个新的组件的时候，是不是mount玩之后立即得到ref     （没问题，可以）
*/

export const TestDemo = () => {

    let [count, setCount] = useState(0)
    const childRef = useRef<Refer>()

    const mountComponent = () => {
        const testRef = {current: null as any}
        const el = document.createElement('div')
        document.body.appendChild(el)
        ReactDOM.render(<Child ref={testRef} name={'111'}/>, el)
        console.log(testRef.current)
    }

    return (
        <div>
            <button onClick={() => setCount(count + 1)}>测试新实例ref以及旧实例unref的执行顺序:{count}</button>
            <button onClick={mountComponent}>测试mount组件之后能不能立即得到ref</button>
            <button onClick={() => childRef.current!.sayHello()}>focus</button>
            <Child key={count} name={'111'} age={11} ref={(val) => {
                console.log('on ref child', val)
                childRef.current = val || undefined
            }}/>
        </div>
    )
}